package test4;

import java.util.concurrent.*;

/**
 * @author liule
 * @date 2023/10/8 9:18
 * @Desc :
 * 当我们有批量执行多个异步任务的业务，并且需要调用get()获取执行结果的时候，我们写的代码一般如下：
 * Future f1 = excutor.submit(c1);
 * f1.get();
 * Future f2 = excutor.submit(c2);
 * f2.get();
 * f1.get()在获取成功之前会被阻塞，会阻塞c2的执行，严重降低了效率。
 * <p>
 * 这时我们可以通过CompletionService来解决这一问题！CompletionSerive接口有一个实现类ExecutorCompletionService
 */
public class ComletionSerbiceTest {
    public static void main(String[] args) {
        BlockingQueue q = new LinkedBlockingQueue();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 3, TimeUnit.SECONDS, q);
        CompletionService<Integer> cs = new ExecutorCompletionService<>(executor);

        cs.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(2000);
                return 1;
            }
        });
        cs.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(2000);
                return 2;
            }
        });
        cs.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(2000);
                return 3;
            }
        });

        for (int i = 0; i < 3; i++) {
            Integer f = null;
            try {
                f = cs.take().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(f);
        }

    }
}
